<template>
  <div class="notice-container">
    <!-- 头部标题与"查看更多" -->
    <div class="notice-header">
      <div class="title-wrapper">
        <el-icon color="#67C23A" :size="18"><Bell /></el-icon>
        <span>最新公告</span>
      </div>
      <el-button type="text" class="more-btn" @click="showAllNotices">
        查看更多
        <el-icon><ArrowRight /></el-icon>
      </el-button>
    </div>

    <!-- 垂直滚动公告轮播 -->
    <el-carousel
        :interval="4000"
        direction="vertical"
        :height="carouselHeight"
        :autoplay="true"
        indicator-position="outside"
        class="notice-carousel"
        @click="handleCarouselClick"
    >
      <el-carousel-item v-for="notice in notices" :key="notice.id">
        <div class="notice-item" @click.stop="showNoticeDetail(notice)">
          <div class="notice-content">
            <div class="notice-meta">
              <div class="notice-tags">
                <el-tag
                    v-for="tag in getTags(notice.tags)"
                    :key="tag"
                    size="small"
                    :type="getTagType(tag)"
                    effect="dark"
                >{{ tag }}</el-tag>
              </div>
              <span class="notice-time">{{ formatTime(notice.time) }}</span>
            </div>
            <div class="notice-title">{{ notice.title }}</div>
            <div class="notice-desc">{{ notice.content }}</div>
          </div>
        </div>
      </el-carousel-item>
    </el-carousel>

    <!-- 全部公告列表对话框 -->
    <el-dialog
        v-model="dialogVisible"
        title="全部公告"
        width="800px"
        custom-class="notice-list-dialog"
    >
      <div class="notice-list" v-loading="dialogLoading">
        <div
            v-for="notice in allNotices"
            :key="notice.id"
            class="notice-list-item"
            @click="showNoticeDetail(notice)"
        >
          <div class="notice-list-content">
            <div class="notice-list-meta">
              <div class="notice-list-tags">
                <el-tag
                    v-for="tag in getTags(notice.tags)"
                    :key="tag"
                    size="small"
                    :type="getTagType(tag)"
                >{{ tag }}</el-tag>
              </div>
              <span class="notice-list-time">{{ formatTime(notice.time, true) }}</span>
            </div>
            <div class="notice-list-title">{{ notice.title }}</div>
          </div>
        </div>
      </div>
      <!-- 分页 -->
      <template #footer>
        <div class="dialog-footer">
          <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :total="total"
              layout="prev, pager, next"
              @current-change="handlePageChange"
          />
        </div>
      </template>
    </el-dialog>

    <!-- 公告详情对话框 -->
    <el-dialog
        v-model="detailVisible"
        width="700px"
        custom-class="notice-detail-dialog"
        :title="currentNotice.title || '公告详情'"
    >
      <div class="notice-detail-header">
        <div class="notice-detail-meta">
          <div class="notice-detail-tags">
            <el-tag
                v-for="tag in getTags(currentNotice.tags)"
                :key="tag"
                size="small"
                :type="getTagType(tag)"
            >{{ tag }}</el-tag>
          </div>
          <span class="notice-detail-time">发布时间：{{ formatTime(currentNotice.time, true) }}</span>
        </div>
      </div>
      <div class="notice-detail-content" v-html="currentNotice.content || '暂无内容'"></div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, defineOptions, watch } from 'vue'
import { ElCarousel, ElCarouselItem, ElButton, ElDialog, ElTag, ElPagination, ElIcon } from 'element-plus'
import { Bell, ArrowRight } from '@element-plus/icons-vue'
import Request from '@/utils/request'

defineOptions({
  name: 'FrontNotice'
})

// 响应式变量
const notices = ref([])
const loading = ref(false)
const dialogVisible = ref(false)
const dialogLoading = ref(false)
const allNotices = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const detailVisible = ref(false)
const currentNotice = ref({})
const carouselHeight = ref('320px')

// 时间格式化
const formatTime = (time, showYear = false) => {
  if (!time) return ''
  const date = new Date(time)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return showYear ? `${year}-${month}-${day}` : `${month}-${day}`
}

// 处理公告标签
const getTags = (tags) => {
  if (!tags) return []
  return typeof tags === 'string' ? tags.split(',') : []
}

// 标签类型映射
const getTagType = (tag) => {
  const typeMap = {
    '重要': 'danger',
    '紧急': 'warning',
    '普通': 'info',
    '公告': 'success'
  }
  return typeMap[tag] || 'info'
}

// 检查文本溢出
const checkTextOverflow = () => {
  const descElements = document.querySelectorAll('.notice-desc')
  descElements.forEach(el => {
    if (el.scrollHeight > el.clientHeight) {
      el.classList.add('truncated')
    } else {
      el.classList.remove('truncated')
    }
  })
}

// 获取轮播公告
const fetchNotices = async () => {
  loading.value = true
  try {
    const res = await Request.get('/notice/page', {
      params: {
        currentPage: 1,
        size: 5
      }
    })
    if (res.code === '0') {
      notices.value = res.data.records || []
      await nextTick()
      checkTextOverflow()
    }
  } catch (error) {
    console.error('获取通知失败:', error)
  } finally {
    loading.value = false
  }
}

// 查看公告详情
const showNoticeDetail = (notice) => {
  if (!notice) return
  console.log('查看公告详情:', notice) // 添加调试日志
  currentNotice.value = { ...notice } // 深拷贝避免引用问题
  detailVisible.value = true
}

// 打开全部公告对话框
const showAllNotices = async () => {
  console.log('打开全部公告') // 添加调试日志
  dialogVisible.value = true
  currentPage.value = 1
  await fetchAllNotices()
}

// 处理轮播点击（用于调试）
const handleCarouselClick = () => {
  console.log('轮播被点击')
}

// 获取全部公告
const fetchAllNotices = async () => {
  dialogLoading.value = true
  try {
    const res = await Request.get('/notice/page', {
      params: {
        currentPage: currentPage.value,
        size: pageSize.value
      }
    })
    if (res.code === '0') {
      allNotices.value = res.data.records || []
      total.value = res.data.total || 0
    }
  } catch (error) {
    console.error('获取所有通知失败:', error)
  } finally {
    dialogLoading.value = false
  }
}

// 分页切换
const handlePageChange = async (page) => {
  currentPage.value = page
  await fetchAllNotices()
}

// 监听对话框显示状态变化，用于调试
watch([dialogVisible, detailVisible], (newValues) => {
  console.log('对话框状态变化:', {
    dialogVisible: newValues[0],
    detailVisible: newValues[1]
  })
})

// 组件挂载时加载数据
onMounted(() => {
  fetchNotices()
})
</script>

<style scoped>
/* 保持原有样式不变 */
.notice-container {
  background: white;
  border-radius: 8px;
  padding: 10px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.notice-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  padding: 0 10px;
}

.title-wrapper {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 500;
  color: #2c3e50;
  flex: 1;
}

.more-btn {
  color: #67C23A;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 4px;
  transition: all 0.3s ease;
  padding: 4px 8px;
  border-radius: 4px;
  background-color: rgba(103, 194, 58, 0.1);
  position: relative;
  z-index: 10;
  cursor: pointer; /* 确保鼠标指针显示为手型 */
}

/* 增加点击区域大小 */
.notice-item, .notice-list-item {
  cursor: pointer;
  /* 增加点击区域 */
  padding: 16px 20px;
  margin: -4px;
}

/* 保持其余样式不变 */
.notice-carousel {
  flex: 1;
  background: #f8faf5;
  border-radius: 8px;
  overflow: hidden;
  height: calc(100% - 50px);
}

.notice-item:hover {
  background: rgba(103, 194, 58, 0.05);
}

.notice-content {
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.notice-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.notice-tags {
  display: flex;
  gap: 6px;
}

.notice-time {
  font-size: 12px;
  color: #909399;
}

.notice-title {
  font-size: 16px;
  font-weight: 500;
  color: #2c3e50;
  margin-bottom: 12px;
  line-height: 1.4;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.notice-desc {
  font-size: 13px;
  color: #606266;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  line-height: 1.6;
  opacity: 0.8;
  flex: 1;
  position: relative;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  max-height: calc(1.6em * 3);
}

.notice-desc::after {
  content: '...';
  position: absolute;
  bottom: 0;
  right: 0;
  padding-left: 40px;
  background: linear-gradient(to right, transparent, #f8faf5 50%);
  display: none;
}

.notice-desc.truncated::after {
  display: block;
}

:deep(.notice-detail-dialog) {
  border-radius: 12px;
  overflow: hidden;
}

:deep(.notice-detail-dialog .el-dialog__header) {
  padding: 20px;
  background: linear-gradient(135deg, #f8faf5, #fff);
  border-bottom: 1px solid #ebeef5;
  margin: 0;
}

:deep(.notice-detail-dialog .el-dialog__title) {
  font-size: 20px;
  font-weight: 600;
  color: #2c3e50;
  line-height: 1.4;
}

:deep(.notice-detail-dialog .el-dialog__headerbtn) {
  top: 20px;
  right: 20px;
}

:deep(.notice-detail-dialog .el-dialog__headerbtn:hover .el-icon-close) {
  color: #67C23A;
}

:deep(.notice-detail-dialog .el-dialog__body) {
  padding: 0;
}

.notice-detail-header {
  padding: 16px 24px;
  background: #f8faf5;
}

.notice-detail-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.notice-detail-tags {
  display: flex;
  gap: 8px;
}

.notice-detail-time {
  font-size: 14px;
  color: #909399;
}

.notice-detail-content {
  padding: 24px;
  font-size: 14px;
  line-height: 1.8;
  color: #606266;
  min-height: 200px;
  max-height: 500px;
  overflow-y: auto;
  white-space: pre-wrap;
  word-break: break-word;
}

.notice-detail-content :deep(p) {
  margin: 0 0 16px;
  white-space: pre-wrap;
  word-break: break-word;
}

.notice-detail-content :deep(img) {
  max-width: 100%;
  height: auto;
  border-radius: 8px;
  margin: 16px 0;
}

.notice-detail-content :deep(a) {
  color: #67C23A;
  text-decoration: none;
  transition: all 0.3s ease;
}

.notice-detail-content :deep(a:hover) {
  color: #85ce61;
  text-decoration: underline;
}

:deep(.notice-list-dialog) {
  border-radius: 12px;
}

:deep(.notice-list-dialog .el-dialog__header) {
  padding: 20px;
  border-bottom: 1px solid #ebeef5;
  margin: 0;
}

:deep(.notice-list-dialog .el-dialog__body) {
  padding: 20px;
  max-height: 600px;
  overflow-y: auto;
}

.notice-list-item {
  padding: 16px;
  border-bottom: 1px solid #ebeef5;
  cursor: pointer;
  transition: all 0.3s ease;
}

.notice-list-item:last-child {
  border-bottom: none;
}

.notice-list-item:hover {
  background: #f8faf5;
}

.notice-list-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.notice-list-tags {
  display: flex;
  gap: 6px;
}

.notice-list-time {
  font-size: 13px;
  color: #909399;
}

.notice-list-title {
  font-size: 15px;
  color: #2c3e50;
  line-height: 1.4;
}

:deep(.notice-list-dialog .el-dialog__footer) {
  padding: 16px 20px;
  border-top: 1px solid #ebeef5;
  text-align: center;
}

:deep(.el-pagination) {
  justify-content: center;
}

:deep(.el-carousel__indicators--vertical) {
  right: 10px;
}

:deep(.el-carousel__indicator--vertical) {
  padding: 3px 0;
}

:deep(.el-carousel__indicator--vertical .el-carousel__button) {
  width: 3px;
  height: 16px;
  background-color: rgba(103, 194, 58, 0.2);
}

:deep(.el-carousel__indicator--vertical.is-active .el-carousel__button) {
  background-color: #67C23A;
}
</style>
